import cache from '@/libs/cache'
import { ACCESS_TOKEN, LOGIN_USER_INFO } from '../mutation-types'
import { login, logout } from '@/apis/modules/baseApi'

const user = {
  state: {
    token: null,
    info: null,
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
      if (token == null) {
        cache.remove(ACCESS_TOKEN)
        return false;
      }
      cache.set(ACCESS_TOKEN, token, 2 * 60 * 60)
    },
    SET_INFO: (state, info) => {
      state.info = info
      if (info == null) {
        cache.remove(LOGIN_USER_INFO)
        return false;
      }
      cache.set(LOGIN_USER_INFO, info, 2 * 60 * 60)
    },

  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(response => {
          const result = response.data
          commit('SET_TOKEN', result.token)
          commit('SET_INFO', result)
          resolve(result)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 登出
    Logout({ commit, state }) {
      return new Promise((resolve) => {
        logout(state.token).then(() => {
          resolve(true)
        }).catch(() => {
          resolve(true)
        }).finally(() => {
          commit('SET_TOKEN', null)
          commit('SET_INFO', null)
        })
      })
    },
  }
}

export default user